package com.missilike.core.aop;

import com.missilike.core.exception.BizException;
import com.missilike.core.exception.SystemException;
import com.missilike.core.result.BaseResultCode;
import com.missilike.core.result.CommonResult;
import com.missilike.core.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author kin
 * @since 2017/12/19
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public CommonResult handleException(final HttpServletRequest request, final Exception ex) {
        log.error(String.format("系统异常:api=%s", request.getRequestURI()), ex);
        return ResultUtils.error();
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public CommonResult handleHttpRequestMethodNotSupportedException() {
        return ResultUtils.error(BaseResultCode.REQUEST_METHOD_NOT_SUPPORTED);
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public CommonResult handleBizException(final BizException e) {
        return ResultUtils.error(e.getCode(), e.getMsg());
    }


    @ExceptionHandler(value = SystemException.class)
    @ResponseBody
    public CommonResult handleBizException(HttpServletRequest request, SystemException e) {
        log.error("Internal error occurred while execute ,with errorCode={}, message={}", e.getCode(), e.getMsg());
        log.error(" Completed execute ServletPath={}", request.getServletPath());
        return ResultUtils.error(e.getCode(), e.getMsg());
    }

}
